<template>
  <main>
    <div>
      <h1>{{type=='add'?'新建小组':type=='set'?'修改小组':''}}</h1>
      <br>
    </div>
    <section v-if="type=='add'">
      <GroupForm ref="addGroup" :fromData="addGroupData"></GroupForm>
      <div class="flex_end">
        <div>
          <el-button type="primary" @click="add_yes">确定</el-button>
          <el-button type="info" @click="no">取消</el-button>
        </div>
      </div>
    </section>
    <section v-if="type=='set'">
      <GroupForm ref="setGroup" :fromData="setGroupData"></GroupForm>
      <div class="flex_end">
        <div>
          <el-button type="primary" @click="set_yes">确定</el-button>
          <el-button type="info" @click="no">取消</el-button>
        </div>
      </div>
    </section>
  </main>
</template>

<script>
import GroupForm from '../formComponent/group_form.vue'
import * as api from '../../../api/private/group'
export default {
  components: {
    GroupForm
  },
  data() {
    return {
      type: '',
      // 新增小组
      addGroupData: {
        deputyGroupLeader: [],
        deviceIdList: [],
        groupLeader: '',
        name: '',
        remark: '',
        userIdList: []
      },
      setGroupData: {
        deputyGroupLeader: [],
        deviceIdList: [],
        groupLeader: '',
        name: '',
        remark: '',
        userIdList: []
      }
    }
  },
  created() {
    this.type = this.$route.query.type
  },
  mounted() {
    if (this.type == 'set') {
      this.$nextTick(item => {
        this.setGroupForm(this.$route.query.data, 'setGroup')
      })
    }
  },
  methods: {
    // 添加确认
    async add_yes() {
      let req = this.addGroupData
      let bol = this.$refs.addGroup.validate()
      if (bol) {
        let res = await api.addGroup(req)
        if (res.code == 0) {
          this.$router.back()
        } else {
          this.$msg.error('新建小组失败')
        }
        // 初始化表单
        this.$refs.addGroup.resetFields()
      }
    },
    // 修改确认
    async set_yes() {
      let req = this.setGroupData
      let bol = this.$refs.setGroup.validate()
      if (bol) {
        let res = await api.setGroup(req)
        if (res.code == 0) {
          this.$router.back()
        } else {
          this.$msg.error('新建小组失败')
        }
        // 初始化表单
        this.$refs.setGroup.resetFields()
      }
    },
    // 通知修改组件发生变化
    setGroupForm(data, ref) {
      this.setGroupData = data
      // 获取指定组件并加工数据为可用
      let catchArray = this.$refs[ref ? ref : 'lookGroup'].catchArray
      catchArray.groupLeaderData = {
        name: data.leaderName,
        id: data.groupLeader
      }
      catchArray.deputyGroupLeaderData = data.deputyGroupLeaderList
      catchArray.userIdListData = data.userList
      catchArray.deviceIdListData = data.deviceList
      catchArray.earlyWarningIdListData = data.earlyWarningList
    },
    no() {
      this.$router.back()
    }
  }
}
</script>

<style>
</style>